import Crypto from 'crypto-js';
import { nanoid } from 'nanoid';

export const REACT_APP_PARAMS_AES_KEY = nanoid(16);
const aesParamsKey = Crypto.enc.Utf8.parse(REACT_APP_PARAMS_AES_KEY);
const iv = Crypto.enc.Utf8.parse(REACT_APP_PARAMS_AES_KEY);

// 报文加密
export function encryptParams(str) {
  const srcStr = Crypto.enc.Utf8.parse(str);
  const encryptStr = Crypto.AES.encrypt(srcStr, aesParamsKey, {
    mode: Crypto.mode.CTR,
    padding: Crypto.pad.Pkcs7,
    iv,
  });
  return encryptStr.ciphertext.toString().toUpperCase();
}

// 报文解密
export function decryptParams(str) {
  try {
    const encryptedHexStr = Crypto.enc.Hex.parse(str);
    const srcStr = Crypto.enc.Base64.stringify(encryptedHexStr);
    const decryptStr = Crypto.AES.decrypt(srcStr, aesParamsKey, {
      mode: Crypto.mode.CTR,
      padding: Crypto.pad.Pkcs7,
      iv,
    });
    const decryptedStr = decryptStr.toString(Crypto.enc.Utf8);
    return decryptedStr.toString();
  } catch (e) {
    return str;
  }
}
